$(function() {
    function getUrlParam(name)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r!=null) return unescape(r[2]); return null; //返回参数值
    }

    var topicId = parseInt(getUrlParam('topicid'));

    var noteTagTemplate = _.template($("#note-tag-template").html());

    /* ------------ tag -------------- */
    function refreshTagTips($container) {
        if($container.find(".tag").length > 0) {
            $container.find(".tag-tips").hide();
        } else {
            $container.find(".tag-tips").show();
        }
    }
    refreshTagTips($(".tags"));
    refreshTagTips($(".places"));

    function refreshProgress() {
        var imgCount = $(".dz-preview").length;
        var progress = 0;
        var note = $(".note-txt").val().trim();
        var tags = getTagString($(".tags"));
        var places = getTagString($(".places"));

        if(imgCount === 1) {
            progress += 50;
        } else if(imgCount >= 2) {
            progress += 70;
        }

        if(note) {
            progress += 10;
        }

        if(tags) {
            progress += 10;
        }

        if(places) {
            progress += 10;
        }

        $(".nt-comp-l").css("width", progress + "%");
        $(".nt-comp-num").text(progress);
    }

    // TODO: 粘贴
    var tagInput = $(".iptwrap .taginput");
    var tagContainer = $(".tags, .places");
    tagInput.on('keypress', function(e) {
        var $this = $(this);
        //; , \n ； ，
        var codeArray = [59, 44, 13, 65307, 65292];
        if(codeArray.indexOf(e.keyCode) >= 0) {
            e.preventDefault();
            e.stopPropagation();

            var noteTagName = $this.val().trim();
            if(!noteTagName) {
                return;
            }

            var newTag = noteTagTemplate({name: noteTagName});
            $(newTag).insertBefore($this.closest(".iptwrap"));

            $this.val("");
            $this.css("width", "0");
            refreshProgress();
            //$(".tags").scrollTop($(".tags").height());
        }
    });

    tagInput.on('keydown', function(e) {
        var $this = $(this);
        // delete
        var noteTagName = $this.val();
        if(noteTagName.length <= 0 && e.keyCode == 8) {
            e.preventDefault();

            $this.closest(".iptwrap").prev().remove();
            refreshTagTips($this.parent().parent());
            refreshProgress();
        }
    });

    tagInput.on("input", function(e) {
        var $this = $(this);
        var $iptwrap = $this.parent();
        var noteTagName = $this.val();

        $this.width($iptwrap.find(".hiddenSpan").text(noteTagName).width());
        $iptwrap.find(".tag-tips").hide();
    });

    tagInput.on("blur", function(e) {
        var $this = $(this);
        var noteTagName = $this.val().trim();
        if(!noteTagName) {
            return;
        }

        var newTag = noteTagTemplate({name: noteTagName});
        $(newTag).insertBefore($this.parent());

        $this.val("");
        $this.css("width", "0");
        refreshProgress();
        //$(".tags").scrollTop($(".tags").height());
    });

    tagContainer.on("click", ".tag", function(e) {
        e.stopPropagation();

        $(this).remove();
        refreshProgress();
    });

    tagContainer.on("click", function(e) {
        $(this).find(".taginput").focus();
    });
    /* ---------------------------- */

    $(".note-txt").on("blur", function() {
        refreshProgress();
    });

    function getTagString($container) {
        var tags = "";

        $container.find(".tag").each(function(index) {
            if(tags) {
                tags += "," + $(this).text();
            } else {
                tags = $(this).text();
            }
        });

        return tags;
    }

    // Change this to the location of your server-side upload handler:
    var uploadUrl = '/api/note/post';
    Dropzone.autoDiscover = false;
    // Now that the DOM is fully loaded, create the dropzone, and setup the
    // event listeners
    var drop_settings = {
        uploadMultiple: true,
        url: uploadUrl,
        acceptedFiles: "image/*",
        paramName: "file",
        dictDefaultMessage: "<i class=\"fa fa-cloud-upload fa-3x fa-green\"></i><br>点击 或 拖放图片到这里上传",
        dictFallbackMessage: "你的浏览器不支持拖放上传",
        autoProcessQueue: false,
        parallelUploads: 12,
        addRemoveLinks: true,
        maxFiles: 12,
        dictRemoveFile: ""
    };
    var dz = new Dropzone(".dropzone", drop_settings);
    dz.on("sendingmultiple", function (file, xhr, formData) {
        formData.append("postData", JSON.stringify({
            idx: 0,
            params:{
                note: $(".note-txt").val().trim(),
                tags: getTagString($(".tags")),
                place: getTagString($(".places")),
                topicid: topicId
            }
        }));
    });

    dz.on("addedfile", function() {
        refreshProgress();
    });

    dz.on("removedfile", function() {
        refreshProgress();
    });

    dz.on('success', function (file, response) {
        if (response && response.ret == -3) {
            window.location.href = "/web/signin"
        }
        window.location.href = '/web/note/list?topicid=' + topicId;
    });

    $(".post-submit").on("click", function() {
        var note = $(".note-txt").val().trim();
        var tags = getTagString($(".tags"));
        var places = getTagString($(".places"));
        var imgCount = $(".dz-preview").length;

        // 至少一张图
        if(!topicId) {
            alert("error");
            return;
        }

        if(imgCount <= 0) {
            $(".error-c").html("请选择至少一张图片");
        }

        $(".dz-remove").hide();
        dz.processQueue();
    });
});
